package cn.toolck.minitomcat.passer;

import cn.toolck.minitomcat.classLoader.MyClassLoader;
import cn.toolck.minitomcat.servlet.HttpServlet;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName XmlPasser
 * @Description TODO
 * @Author Toolck Rin
 * @Date 2021/3/17 11:43
 * @Version 1.0
 **/
public class WebXmlPasser extends Passer {
    public WebXmlPasser(String fileName) {
        super(fileName);
    }

    public WebXmlPasser(String fileName, MyClassLoader myClassLoader) {
        super(fileName,myClassLoader);
    }

    public <T> Map<String, HttpServlet> passFile() {
        Element rootElement = getDocument().getRootElement();
        List<Element> selectNodes = rootElement.selectNodes("//servlet");
        Map<String, HttpServlet> servletMap = new HashMap<>();
        for (int i = 0; i < selectNodes.size(); i++) {
            Element element = selectNodes.get(i);
            // <servlet-name>lagou</servlet-name>
            Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
            String servletName = servletnameElement.getStringValue();
            // <servlet-class>server.LagouServlet</servlet-class>
            Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
            String servletClass = servletclassElement.getStringValue();


            // 根据servlet-name的值找到url-pattern
            Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
            // /lagou
            String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

            try {
                servletMap.put(urlPattern, (HttpServlet) getClassLoader().loadClass(servletClass).newInstance());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return servletMap;
    }
}
